<template>
  <div class="supplier-profile-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>供应商档案</span>
        </div>
      </template>

      <!-- 查询条件 -->
      <el-form :model="queryForm" label-width="120px" class="query-form">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="数据库连接">
              <el-select 
                v-model="queryForm.databaseId" 
                placeholder="请选择数据库"
                style="width: 100%"
                @change="handleDatabaseChange"
              >
                <el-option
                  v-for="db in databaseList"
                  :key="db.id"
                  :label="db.name"
                  :value="db.id"
                  :disabled="!db.name.includes('总部')"
                >
                  <span>{{ db.name }}</span>
                  <span v-if="!db.name.includes('总部')" style="color: #999; font-size: 12px; margin-left: 8px;">
                    (此报表仅支持总部数据库)
                  </span>
                </el-option>
              </el-select>
              <div class="form-tip">
                <el-icon color="#E6A23C"><Warning /></el-icon>
                此报表只能选择总部进行查询
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="编号或名称">
              <el-input
                v-model="queryForm.keyword"
                placeholder="请输入编号或名称"
                clearable
                @keyup.enter="handleQuery"
              >
                <template #prefix>
                  <el-icon><Search /></el-icon>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24" style="text-align: right;">
            <el-button type="primary" @click="handleQuery" :loading="loading">
              <el-icon><Search /></el-icon>
              查询
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
            <el-button 
              type="success" 
              @click="handleExport" 
              :disabled="tableData.length === 0"
              plain
            >
              <el-icon><Download /></el-icon>
              导出Excel
            </el-button>
          </el-col>
        </el-row>
      </el-form>

      <!-- 数据表格 -->
      <div class="table-container">
        <el-table 
          :data="tableData" 
          border 
          style="width: 100%"
          v-loading="loading"
          :height="tableHeight"
          stripe
        >
          <el-table-column type="index" label="序号" width="60" align="center" fixed />
          <el-table-column prop="code" label="编码" width="120" fixed />
          <el-table-column prop="name" label="供应商名称" width="200" show-overflow-tooltip />
          <el-table-column prop="bank" label="开户行" width="180" show-overflow-tooltip />
          <el-table-column prop="bankAccount" label="银行账号" width="180" />
          <el-table-column prop="region" label="区域" width="100" />
          <el-table-column prop="remark" label="备注信息" width="150" show-overflow-tooltip />
          <el-table-column prop="businessMode" label="经营方式" width="100" />
          <el-table-column prop="contact" label="联系人" width="100" />
          <el-table-column prop="mobile" label="手机" width="120" />
          <el-table-column prop="phone" label="电话" width="120" />
          <el-table-column prop="defaultRate" label="默认扣率" width="100" align="right">
            <template #default="scope">
              {{ scope.row.defaultRate }}%
            </template>
          </el-table-column>
          <el-table-column prop="address" label="地址" width="200" show-overflow-tooltip />
          <el-table-column prop="email" label="邮箱" width="180" show-overflow-tooltip />
          <el-table-column prop="minAmount" label="保底金额" width="120" align="right">
            <template #default="scope">
              ￥{{ scope.row.minAmount.toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column prop="paymentMethod" label="付款方式" width="120" />
          <el-table-column prop="status" label="状态" width="80" align="center">
            <template #default="scope">
              <el-tag :type="scope.row.status === '0' ? 'success' : 'info'">
                {{ scope.row.status === '0' ? '正常' : '停用或冻结' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="businessLicense" label="营业执照号" width="180" />
          <el-table-column prop="taxNo" label="税务登记号" width="180" />
        </el-table>

        <!-- 汇总行 -->
        <div class="summary-bar">
          <div class="summary-item">
            <span class="summary-label">查询结果：</span>
            <span class="summary-value">共 <strong>{{ totalCount }}</strong> 条供应商数据</span>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, Refresh, Warning, Download } from '@element-plus/icons-vue'
import { getDatabaseList } from '@/api/database'
import { API_BASE_URL } from '@/config/api'
import * as XLSX from 'xlsx'

interface DatabaseItem {
  id: number
  name: string
}

interface QueryForm {
  databaseId: number | null
  keyword: string
}

interface TableRow {
  code: string
  name: string
  bank: string
  bankAccount: string
  region: string
  remark: string
  businessMode: string
  contact: string
  mobile: string
  phone: string
  defaultRate: number
  address: string
  email: string
  minAmount: number
  paymentMethod: string
  status: string
  businessLicense: string
  taxNo: string
}

const loading = ref(false)
const tableHeight = ref(500)
const databaseList = ref<DatabaseItem[]>([])
const tableData = ref<TableRow[]>([])

const queryForm = reactive<QueryForm>({
  databaseId: null,
  keyword: ''
})

// 计算汇总数据
const totalCount = computed(() => tableData.value.length)

// 加载数据库列表
const loadDatabaseList = async () => {
  try {
    const res = await getDatabaseList()
    if (res.success && res.data) {
      databaseList.value = res.data
      // 自动选择名称包含"总部"的数据库
      const headquartersDb = databaseList.value.find(db => db.name.includes('总部'))
      if (headquartersDb) {
        queryForm.databaseId = headquartersDb.id
      }
    }
  } catch (error) {
    console.error('加载数据库列表失败:', error)
  }
}

// 数据库切换
const handleDatabaseChange = (value: number) => {
  const selectedDb = databaseList.value.find(db => db.id === value)
  if (selectedDb && !selectedDb.name.includes('总部')) {
    ElMessage.warning('此报表只能选择总部数据库进行查询')
    // 清空选择
    queryForm.databaseId = null
  }
  // 清空表格数据
  tableData.value = []
}

// 查询
const handleQuery = async () => {
  if (!queryForm.databaseId) {
    ElMessage.warning('请选择总部数据库连接')
    return
  }

  const selectedDb = databaseList.value.find(db => db.id === queryForm.databaseId)
  if (selectedDb && !selectedDb.name.includes('总部')) {
    ElMessage.warning('此报表只能选择总部数据库进行查询')
    return
  }

  loading.value = true
  
  try {
    // 调用后端API
    const response = await fetch(`${API_BASE_URL}/api/report/supplier-profile`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        databaseId: queryForm.databaseId,
        keyword: queryForm.keyword || ''
      })
    })

    const result = await response.json()
    
    if (result.success) {
      tableData.value = result.data || []
      ElMessage.success(`查询成功，共 ${tableData.value.length} 条供应商数据`)
    } else {
      ElMessage.error(result.message || '查询失败')
      tableData.value = []
    }
  } catch (error) {
    console.error('查询失败:', error)
    ElMessage.error('查询失败，请检查网络连接')
    tableData.value = []
  } finally {
    loading.value = false
  }
}

// 重置
const handleReset = () => {
  queryForm.keyword = ''
  tableData.value = []
}

// 导出Excel
const handleExport = () => {
  if (tableData.value.length === 0) {
    ElMessage.warning('没有可导出的数据')
    return
  }

  try {
    // 准备导出的数据
    const exportData = tableData.value.map((item, index) => ({
      '序号': index + 1,
      '编码': item.code,
      '供应商名称': item.name,
      '开户行': item.bank,
      '银行账号': item.bankAccount,
      '区域': item.region,
      '备注信息': item.remark,
      '经营方式': item.businessMode,
      '联系人': item.contact,
      '手机': item.mobile,
      '电话': item.phone,
      '默认扣率': item.defaultRate + '%',
      '地址': item.address,
      '邮箱': item.email,
      '保底金额': '￥' + item.minAmount.toFixed(2),
      '付款方式': item.paymentMethod,
      '状态': item.status === '1' ? '正常' : '停用',
      '营业执照号': item.businessLicense,
      '税务登记号': item.taxNo
    }))

    // 创建工作表
    const worksheet = XLSX.utils.json_to_sheet(exportData)

    // 设置列宽
    const colWidths = [
      { wch: 6 },  // 序号
      { wch: 15 }, // 编码
      { wch: 25 }, // 供应商名称
      { wch: 20 }, // 开户行
      { wch: 20 }, // 银行账号
      { wch: 10 }, // 区域
      { wch: 20 }, // 备注信息
      { wch: 12 }, // 经营方式
      { wch: 10 }, // 联系人
      { wch: 15 }, // 手机
      { wch: 15 }, // 电话
      { wch: 12 }, // 默认扣率
      { wch: 30 }, // 地址
      { wch: 25 }, // 邮箱
      { wch: 15 }, // 保底金额
      { wch: 12 }, // 付款方式
      { wch: 8 },  // 状态
      { wch: 20 }, // 营业执照号
      { wch: 20 }  // 税务登记号
    ]
    worksheet['!cols'] = colWidths

    // 创建工作簿
    const workbook = XLSX.utils.book_new()
    XLSX.utils.book_append_sheet(workbook, worksheet, '供应商档案')

    // 生成文件名（带时间戳）
    const now = new Date()
    const fileName = `供应商档案_${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}_${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}${String(now.getSeconds()).padStart(2, '0')}.xlsx`

    // 导出文件
    XLSX.writeFile(workbook, fileName)

    ElMessage.success(`成功导出 ${tableData.value.length} 条供应商数据`)
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败，请重试')
  }
}

onMounted(() => {
  loadDatabaseList()
  // 计算表格高度
  tableHeight.value = window.innerHeight - 400
})
</script>

<style scoped>
.supplier-profile-container {
  width: 100%;
}

.card-header {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.query-form {
  margin-bottom: 20px;
  padding: 20px;
  background: #f5f7fa;
  border-radius: 4px;
}

.form-tip {
  display: flex;
  align-items: center;
  gap: 4px;
  margin-top: 4px;
  font-size: 12px;
  color: #E6A23C;
}

.table-container {
  margin-top: 20px;
}

.summary-bar {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  margin-top: 16px;
  padding: 16px 20px;
  background: #f5f7fa;
  border-radius: 4px;
}

.summary-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.summary-label {
  font-size: 14px;
  color: #606266;
}

.summary-value {
  font-size: 16px;
  color: #303133;
}

.summary-value strong {
  color: #409eff;
  font-size: 20px;
}
</style>
